package com.lucenly.card.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lucenly.card.R;
import com.lucenly.card.base.BaseActivity;

import butterknife.BindView;
import ezy.ui.layout.LoadingLayout;

public class WebViewActivity extends BaseActivity {
    @BindView(R.id.mViewParent)
    WebView webview;
    @BindView(R.id.view)
    LoadingLayout view1;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.rl_title)
    RelativeLayout rl_title;
    String path = "http://www.baidu.com";
    int type = 0;
    String title = "详情";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
    }

    @Override
    protected void initView() {
        type = getIntent().getIntExtra("type", 0);
        if(type==0){
            rl_title.setVisibility(View.GONE);
        }else{
            rl_title.setVisibility(View.VISIBLE);
            ll_back.setVisibility(View.VISIBLE);
            tv_title.setText(title);
        }
        path = getIntent().getStringExtra("path");
        Log.v("path===",path);
//        webview = new X5WebView(this, null);
//        mViewParent.addView(webview, new FrameLayout.LayoutParams(
////                FrameLayout.LayoutParams.FILL_PARENT,
////                FrameLayout.LayoutParams.FILL_PARENT));
        WebSettings settings = webview.getSettings();
        //配置支持domstorage
        settings.setDomStorageEnabled(true);//启用或禁用DOM缓存
        //settings.setBuiltInZoomControls(false);//是否显示缩放按钮，默认false
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        webview.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
    }

    @Override
    protected void bindEvent() {
        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        view1.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webview.loadUrl(path);
            }
        });
//        webview.setWebChromeClient(new MyWebChromeClient());
        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                result.cancel();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url,
                                       String message, final JsResult result) {
                // TODO Auto-generated method stub
                return true;
            }
        });
        webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url.toString());
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view1.showContent();
                //这段js函数的功能就是注册监听，遍历所有的img标签，并添加onClick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
                view.loadUrl("javascript:(function(){"+
                        "                        var back = document.getElementsByClassName(\"back\")[0];\n" +
                        "                        back.onclick=function() {\n" +
                        "                           window.imagelistner.goback();  \n" +
                        "                           };\n"
                        + "var objs = document.getElementsByClassName(\"msgdetails_cont\")[0].getElementsByTagName(\"img\");"
                        + "for(var i=0;i<objs.length;i++)  " + "{"
                        + "    objs[i].onclick=function()  " + "    {  "
                        + "        window.imagelistner.openImage(this.src);  "
                        + "    }  " + "}" + "})()");

            }
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
                view1.showError();
            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
//                view1.setErrorText("网络连接缓慢，暂时无法加载!").showError();
            }
        });
        webview.setDownloadListener(new MyWebViewDownLoadListener());
        webview.loadUrl(path);
    }
    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }
    @Override
    protected void initData() {

    }
    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || webview == null || intent.getData() == null)
            return;
        webview.loadUrl(intent.getStringExtra("path").toString());
    }
    @Override
    protected void processClick(View view) {

    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }

    // js通信接口
    public class JavascriptInterface {

        private Context context;


        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            System.out.println(img);
        }
        @android.webkit.JavascriptInterface
        public void goback() {
            System.out.println("点击事件");
            finish();
        }
    }
}
